﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Newtonsoft.Json;
using QuTouTiaoAssist.Entity;
using QuTouTiaoAssist.Util;

namespace QuTouTiaoAssist
{
    public partial class FrmReadArticleHalfAuto : FrmBase
    {
        private bool m_isReading = false;
        private List<QttChannelInfo> m_channelList = new List<QttChannelInfo>();
        private bool m_stopWhenTwoSuccess = false;

        public FrmReadArticleHalfAuto()
        {
            InitializeComponent();
            ClearControls();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!CheckLogin())
                return;

            if (m_isReading)
                return;

            string url = this.textBox1.Text.Trim();
            if (!url.StartsWith("http://api.1sapp.com/content/getList?"))
            {
                MsgBox.ShowInfo("请输入有效的URL！");
                return;
            }
            m_stopWhenTwoSuccess = this.chkBoxStopWhenTwoSuccess.Checked;

            ClearControls();

            new Thread(() =>
            {
                m_isReading = true;
                int successNum = 0;
                int successcoins = 0;
                try
                {
                    var str = HttpUtil.GetResponseString(url, HttpMethod.GET, null);

                    #region 定义返回数据类型
                    var type = new
                    {
                        data = new
                        {
                            data = new[]
                                {
                                    new
                                    {
                                        id = "",
                                        title = "",
                                        read_count = "",
                                        share_count = "",
                                        comment_count = "",
                                        url = "",
                                        introduction = "",
                                        publish_time = "",
                                    }
                                }
                        }
                    };
                    #endregion

                    var typeValue = JsonConvert.DeserializeAnonymousType(str, type);

                    int length = typeValue.data.data.Length;

                    #region 填充ListView数据
                    for (int i = 0; i < length; i++)
                    {
                        var item = typeValue.data.data[i];
                        if (item.url == null) // 过滤没有url的文章
                            continue;

                        int newRowIndex = AppendToListView(new List<string>
                                {
                                    (i+1).ToString(),
                                    item.title,
                                    OtherUtil.UnixTimeInMillis2DateTime(Convert.ToInt64(item.publish_time)).ToString(),
                                    ""
                                });

                        SetListViewTag(this.listView1, newRowIndex, item.url);
                    }
                    #endregion

                    #region 读取文章
                    int count = this.listView1.Items.Count;
                    for (int i = 0; i < count; i++)
                    {
                        var articleUrl = GetListViewTag(this.listView1, i) as string;
                        var resultStr = "";
                        try
                        {
                            var readResult = QttHelper.ReadArticle(base.MemberInfo.MemberId, base.MemeberToken, articleUrl);
                            if (readResult.Code == 0)
                            {
                                resultStr = "阅读+" + readResult.Data.Amount + "金币";
                                successNum++;
                                successcoins += readResult.Data.Amount;
                            }
                            else
                            {
                                throw new Exception(readResult.Message + readResult.Code);
                            }
                        }
                        catch (Exception ex)
                        {
                            resultStr = "阅读失败，" + ex.Message;
                        }
                        SetListViewItemText(this.listView1, i, 3, resultStr);

                        if (m_stopWhenTwoSuccess && successNum >= 2)
                        {
                            break;
                        }

                        Thread.Sleep(1000);
                    }
                    #endregion

                    MsgBox.ShowInfo(string.Format("成功：{0}个，获取金币：{1}", successNum, successcoins));

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                m_isReading = false;
            }).Start();
        }

        private int AppendToListView(List<string> objs)
        {
            if (this.InvokeRequired)
            {
                return (int)this.Invoke(new Func<List<string>, int>(AppendToListView), objs);
            }
            this.listView1.Items.Add(new ListViewItem(objs.ToArray()));
            return this.listView1.Items.Count - 1;
        }

        private void SetListViewTag(ListView listView, int rowIndex, object obj)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<ListView, int, object>(SetListViewTag), listView, rowIndex, obj);
                return;
            }
            this.listView1.Items[rowIndex].Tag = obj;
        }

        private object GetListViewTag(ListView listView, int rowIndex)
        {
            if (this.InvokeRequired)
            {
                return this.Invoke(new Func<ListView, int, object>(GetListViewTag), listView, rowIndex);
            }
            return this.listView1.Items[rowIndex].Tag;
        }

        private void SetListViewItemText(ListView listView, int rowIndex, int columnIndex, object value)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<ListView, int, int, object>(SetListViewItemText), listView, rowIndex, columnIndex, value);
                return;
            }
            this.listView1.Items[rowIndex].SubItems[columnIndex].Text = value.ToString();
        }

        private void ClearControls()
        {
            this.listView1.Items.Clear();
        }

        private void FrmReadArticleHalfAuto_Load(object sender, EventArgs e)
        {
            InitChannelList();
        }

        private void InitChannelList()
        {
            new Thread(() => { m_channelList = QttHelper.GetDefaultChannelList().Data; }).Start();
        }

        private void btnSelectChannel_Click(object sender, EventArgs e)
        {
            ContextMenuStrip cms = new ContextMenuStrip();
            foreach (var info in m_channelList)
            {
                cms.Items.Add(info.Name, null, (o, args) =>
                {
                    ToolStripItem item = o as ToolStripItem;
                    int id = (int) item.Tag;
                    this.textBox1.Text = QttHelper.GenArticleChannelUrl(id, 1);
                }).Tag = info.Id;
            }
            cms.Show(this.btnSelectChannel, new Point(0,this.btnSelectChannel.Height));
        }
    }
}
